<?php

namespace app\admin\service\common;

use app\admin\model\auth\AdminModel;
use app\admin\model\common\UploadModel;
use app\admin\model\common\UploadCateModel;
use app\admin\model\user\UsersModel;
use think\facade\Db;
use app\admin\service\BaseService;

class UploadService extends BaseService
{
    //添加资源类型
    public function Add($data)
    {
        $model = new UploadCateModel();
        
        $Unique = ['name'];
        $empty = ['name'];
        $check = $this->checkParams($model, $data, $Unique, $empty);
        if ($check !== true) {
            return fail($check['msg']);
        }
        
        $data['created_at'] = time();
        Db::startTrans();
            try{
                $model->insertGetId($data);
                Db::commit();
                $this->writeLog('添加', 1);
                return success();
            } catch (\Exception $e) {
                Db::rollback();
                return fail('操作失败:' . $e->getMessage());
        }
    }
    //编辑资源类型
    public function Edit($id, $data)
    {
        $model = new UploadCateModel();
        $res = $model->where('id', $id)->find();
        if (empty($res)) {
            return fail('用户不存在');
        }
        $Unique = ['name'];
        $empty = ['name'];
        $data['id'] = $id;
        $check = $this->checkParams($model, $data, $Unique, $empty);
        if ($check !== true) {
            return fail($check['msg']);
        }
        
        Db::startTrans();
        unset($data['id']);
            try{
                $data['updated_at'] = time();
                $model->where('id', $id)->update($data);
                Db::commit();
                $this->writeLog('编辑', 2);
                return success();
            } catch (\Exception $e) {
                Db::rollback();
                return fail('操作失败:' . $e->getMessage());
        }
    }
    //删除资源类型
    public function delCate($ids)
    {
      $model = new UploadCateModel();
      $uploadModel = new UploadModel();
      $ids = array_filter(array_unique($ids));
      if (empty($ids)) {
          return fail('请选择要删除的数据');
      }
      foreach ($ids as $id) {
          if (!is_numeric($id) || $id <= 0) {
              return fail('包含错误ID值'.$id);
          }
        $count = $uploadModel->where('cate_id', $id)->count();
        if ($count > 0) {
            return fail('分类ID '.$id.' 下存在配置数据，无法删除');
        }
      }
      $ids = array_map('intval', $ids);
      Db::startTrans();
        try{
            $model->whereIn('id', $ids)->delete();
            Db::commit();
            $this->writeLog('删除'. implode(',', $ids), 3);
            return success();
        } catch (\Exception $e) {
            Db::rollback();
            return fail('操作失败:' . $e->getMessage());
        }
    }
    /**
     * 获取资源列表
     * @param $data
     * @return mixed
     */
    public function getList($param)
    {
        $model = new UploadModel();
        $admin = new AdminModel();
        $user = new UsersModel();
        $searchFields = ['file_name', 'extension', 'url'];//模糊搜索
        $search = ['app','cate_id'];//精准搜索
        $fields = [];//查询字段
        $list = $this->paginateWithSearch($model, $param, $fields, $searchFields, $search ,'created_at','desc');
        foreach ($list['data'] as &$v) {
            if (($v['app'] ?? 0) == 2) {
                $username = $admin->where('id', $v['user_id'])->value('username');
                $v['username'] = $username !== null ? (string)$username : '';
            } else {
                $phone = $user->where('id', $v['user_id'])->value('phone');
                $v['username'] = $phone !== null ? (string)$phone : '';
            }
        }
        unset($v);
        return success($list);
    }
    //删除资源
    public function Delete($ids)
    {
      $model = new UploadModel();
      $ids = array_filter(array_unique($ids));
      if (empty($ids)) {
          return fail('请选择要删除的数据');
      }
      foreach ($ids as $id) {
          if (!is_numeric($id) || $id <= 0) {
              return fail('包含错误ID值'.$id);
          }
      }
      $ids = array_map('intval', $ids);
      $ok = $model->deleteByIds($ids);
      if ($ok) {
        $this->writeLog('删除' . implode(',', $ids), 3);
        return success([],'删除成功');
      } else {
        return fail('删除失败，查看日志获取详细信息');
      }
    }
    //移动资源
    public function Move($id, $data)
    {
        $model = new UploadModel();
        $res = $model->where('id', $id)->find();
        if (empty($res)) {
            return fail('用户不存在');
        }
        $Unique = [];
        $empty = [];
        $data['id'] = $id;
        $check = $this->checkParams($model, $data, $Unique, $empty);
        if ($check !== true) {
            return fail($check['msg']);
        }
        
        Db::startTrans();
        unset($data['id']);
        try{
            $data['updated_at'] = time();
            $model->where('id', $id)->update($data);
            Db::commit();
            $this->writeLog('编辑', 2);
            return success();
        } catch (\Exception $e) {
            Db::rollback();
            return fail('操作失败:' . $e->getMessage());
        }
    }
    
}
